﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.SCUserService;
using System.Text.RegularExpressions;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace SalaryChannel
{
    public partial class UserManage : UserControl
    {

        private UserServiceClient _userService = null;
        private static OperationContext _userPC = null;
        public UserServiceClient UserService
        {
            get
            {
                if (_userService == null)
                {
                    _userService = new UserServiceClient();

                    OperationContext.Current = new OperationContext((IContextChannel)_userService.InnerChannel);
                    MessageHeader header = MessageHeader.CreateHeader("uafcztga", "", ServiceInstance.UserName);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    header = MessageHeader.CreateHeader("xufasft", "", ServiceInstance.Password);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    _userPC = OperationContext.Current;
                }
                else
                {
                    OperationContext.Current = _userPC;
                }
                return _userService;
            }
            set { _userService = value; }
        }
        public UserManage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(UserManage_Loaded);
            //this.IsEmpty = false;
            this.LevelCBox.ItemsSource = new string[] { "正常", "删除" };//, "超级管理员","业务支撑中心管理员", "市渠道管理员", "县渠道管理员" };

            UserService.QueryUserInforByIDCompleted += new EventHandler<QueryUserInforByIDCompletedEventArgs>(dclient_QueryUserInforCompleted);
            UserService.DeleteUserCompleted += new EventHandler<DeleteUserCompletedEventArgs>(dclient_DeleteUserCompleted);
            UserService.AddUserCompleted += new EventHandler<AddUserCompletedEventArgs>(dclient_AddUserCompleted);
            UserService.QueryUserInforByChannelCompleted += new EventHandler<QueryUserInforByChannelCompletedEventArgs>(UserClient_QueryUserInforByChannelCompleted);
            UserService.UpdateUserCompleted += new EventHandler<UpdateUserCompletedEventArgs>(UserClient_UpdateUserCompleted);
            UserService.GetUserAuthCompleted += new EventHandler<GetUserAuthCompletedEventArgs>(UserClient_GetUserAuthCompleted);
            UserService.UpdateUserAuthCompleted += new EventHandler<UpdateUserAuthCompletedEventArgs>(UserClient_UpdateUserAuthCompleted);

            AuthsGrid.SelectionChanged += new SelectionChangedEventHandler(AuthsGrid_SelectionChanged);
            UserService.GetAreaCompleted += new EventHandler<GetAreaCompletedEventArgs>(UserService_GetAreaCompleted);
            UserService.GetDistrictCompleted += new EventHandler<GetDistrictCompletedEventArgs>(UserService_GetDistrictCompleted);
            UserService.UpdateChannelCompleted += new EventHandler<UpdateChannelCompletedEventArgs>(UserService_UpdateChannelCompleted);
            UserService.GetChannelCompleted += new EventHandler<GetChannelCompletedEventArgs>(UserService_GetChannelCompleted);
        }



        static Regex ChannelRegex = new Regex(@"^[1-9]\d{7}$");

        void UserManage_Loaded(object sender, RoutedEventArgs e)
        {

           
        }


        void UserClient_UpdateUserCompleted(object sender, UpdateUserCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.Succeeded, Title.Information);
                }
                else
                {
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Information);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Information);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        void UserClient_QueryUserInforByChannelCompleted(object sender, QueryUserInforByChannelCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询用户失败！", Title.Warning);
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有符合条件的用户！", Title.Warning);

                }
                else
                {
                    this.ResultGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取查询结果失败", Title.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }


        public void Initailize()
        {
            Clear();

            this.QueryBtn.Visibility = Visibility.Collapsed;
            this.DelUserBtn.Visibility = Visibility.Collapsed;
            this.UpdateUserBtn.Visibility = Visibility.Collapsed;
            this.AddUserBtn.Visibility = Visibility.Collapsed;

            this.AuthPage.Tag = null;
            this.SelectedUserTB.Text = "请先选择一位用户";
            this.AuthsGrid.ItemsSource = null;

            IsReadOnly = true;
            AuthPage.Visibility = App.IsAuth(18) ? Visibility.Visible : Visibility.Collapsed;

            if (AreaCBox.Items.Count == 0)
            {
                UserService.GetAreaAsync(App.CurrentUser.CityCode);
            }

            QueryBtn2.IsEnabled = true;
            NewBtn2.IsEnabled = true;
            UpdateBtn2.IsEnabled = false;
            CmtBtn2.IsEnabled = false;
            ClearBtn2.IsEnabled = false;
            ClearBtn2_Click(null, null);
        }

        private bool _isReadOnly = true;

        public bool IsReadOnly
        {
            get { return _isReadOnly; }
            set
            {
                _isReadOnly = value;
                this.StaffIDTB.IsReadOnly = value;
                this.StaffNameTB.IsReadOnly = value;
                this.ChannelIDTB.IsReadOnly = value;
                this.ChannelNameTB.IsReadOnly = value;
                this.PasswordTB.IsEnabled = !value;
                this.LevelCBox.IsEnabled = !value;
                this.EmailTB.IsReadOnly = value;
                this.TelTB.IsReadOnly = value;
            }
        }

        public void Clear()
        {

            this.StaffIDTB.Text = string.Empty;
            this.StaffNameTB.Text = string.Empty;
            this.ChannelIDTB.Text = string.Empty;
            this.ChannelNameTB.Text = string.Empty;
            this.PasswordTB.Password = string.Empty;
            this.TelTB.Text = string.Empty;
            this.EmailTB.Text = string.Empty;
            this.LevelCBox.SelectedIndex = -1;
            this.ResultGrid.ItemsSource = null;
            this.QueryRBtn.IsChecked = false;
            this.AddRBtn.IsChecked = false;
            this.IDCBox.IsChecked = false;

        }
      

        private void QueryBtn_Click(object sender, RoutedEventArgs e)
        {
            
            try
            {
                if (IDCBox.IsChecked.Value)
                {
                    if (string.IsNullOrEmpty(this.StaffIDTB.Text)
                        && string.IsNullOrEmpty(this.StaffNameTB.Text))
                    {
                        App.MessageBox.ShowDialog("工号或姓名不能同时为空!", Title.Warning);
                        return;
                    }

                   UserService.QueryUserInforByIDAsync(this.StaffIDTB.Text,
                        this.StaffNameTB.Text);

                   
                }
                else if (ChannelCBox.IsChecked.Value)
                {
                    if (string.IsNullOrEmpty(this.ChannelIDTB.Text)
                        && string.IsNullOrEmpty(this.ChannelNameTB.Text))
                    {
                        App.MessageBox.ShowDialog("渠道编号或名称不能同时为空!", Title.Warning);
                        return;
                    }
                   UserService.QueryUserInforByChannelAsync(this.ChannelIDTB.Text,
                        this.ChannelNameTB.Text);
                }
                else
                {
                    App.MessageBox.ShowDialog("请至少设置一项查询条件！", Title.Warning);
                    return;
                }
                this.Cursor = Cursors.Wait;
                this.ResultGrid.ItemsSource = null;
            }
            catch 
            {
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                
            }

        }
        void dclient_QueryUserInforCompleted(object sender, QueryUserInforByIDCompletedEventArgs e)
        {
            try
            {

                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询用户失败！", Title.Warning);
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有符合条件的用户！", Title.Warning);

                }
                else
                {
                    this.ResultGrid.ItemsSource = e.Result;
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("获取查询结果失败" , Title.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void AddUserBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.StaffIDTB.Text)
                || string.IsNullOrEmpty(this.StaffNameTB.Text)
                || string.IsNullOrEmpty(this.ChannelIDTB.Text)
                || string.IsNullOrEmpty(this.PasswordTB.Password)
                || string.IsNullOrEmpty(this.TelTB.Text)
                || string.IsNullOrEmpty(this.EmailTB.Text)
                || this.LevelCBox.SelectedIndex < 0)
            {
                App.MessageBox.ShowDialog("请完整填写所有信息!", Title.Warning);
                return;
            }
            if (this.ChannelIDTB.Text.Length != 8)
            {
                App.MessageBox.ShowDialog("请正确填写8位的渠道编号!", Title.Warning);
                return;
            }
            Regex email = new Regex(DataHelper.EmailRegexString);
            if (!email.IsMatch(EmailTB.Text))
            {
                App.MessageBox.ShowDialog("请正确填写邮箱地址", Title.Warning);
                return;
            }

            App.MessageBox.ShowDialog("是否确认增加该用户?", new Action(AddUserAction), Title.Information);
           
           
        }
        void AddUserAction()
        {
            try
            {
                UserInfor ui =new UserInfor {
                    User_ID = this.StaffIDTB.Text,
                    UserName = StaffNameTB.Text,
                    Channel_ID = ChannelIDTB.Text,
                    Password = PasswordTB.Password,
                     Email=EmailTB.Text,
                     Tel=TelTB.Text,
                     IsDel=(LevelCBox.SelectedIndex==0?'0':'1'),
                     CreateID=App.CurrentUser.UserID,
                     CreateTime=DateTime.Now
                };
               UserService.AddUserAsync(ui);
                    //(this.StaffIDTB.Text, StaffNameTB.Text, ChannelIDTB.Text, ChannelNameTB.Text,
                    //    PasswordTB.Password, LevelCBox.SelectedIndex, TelTB.Text, EmailTB.Text);

                this.Cursor = Cursors.Wait;
            }
            catch
            {
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);

            }
        }
       void dclient_AddUserCompleted(object sender, AddUserCompletedEventArgs e)
        {
            string msg = string.Empty;
            try
            {
                if (e.Result==("true"))
                {
                    msg = "增加用户成功!";
                    this.IsReadOnly = true;
                }
                else
                {
                    msg = "增加用户失败:" + e.Result;

                }
            }
            catch (Exception ex)
            {
                msg = "增加用户异常：" + ex.Message;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(msg, Title.Information);
            }
            
        }
        private void QueryRBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.QueryRBtn.IsChecked.Value)
            {
                this.PasswordTB.IsEnabled = false;
                this.LevelCBox.IsEnabled = false;

                this.StaffNameTB.IsReadOnly = false;
                this.StaffIDTB.IsReadOnly = false;
                this.ChannelIDTB.IsReadOnly = true;
                this.ChannelNameTB.IsReadOnly = true;

                IDCBox.IsChecked = true;
                ChannelCBox.IsChecked = false;


                this.QueryBtn.Visibility = Visibility.Visible;
                this.DelUserBtn.Visibility = Visibility.Visible;
                this.AddUserBtn.Visibility = Visibility.Collapsed;
                this.UpdateUserBtn.Visibility = Visibility.Visible;
            }

        }

        private void AddRBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.AddRBtn.IsChecked.Value)
            {
               
                this.QueryBtn.Visibility = Visibility.Collapsed;
                this.DelUserBtn.Visibility = Visibility.Collapsed;
                this.UpdateUserBtn.Visibility = Visibility.Collapsed;
                this.AddUserBtn.Visibility = Visibility.Visible;

                Clear();
                IsReadOnly = false;
                this.AddRBtn.IsChecked = true;
                this.ChannelNameTB.IsReadOnly = true;                
            }
        }

        void DelUserAction()
        {
           UserService.DeleteUserAsync((this.ResultGrid.SelectedItem as SCUserService.VW_UserWithChannel).UserID,App.CurrentUser.UserID);
            this.Cursor = Cursors.Wait;
        }
        private void DelUserBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.ResultGrid.SelectedIndex < 0 || this.ResultGrid.ItemsSource == null)
            {
                App.MessageBox.ShowDialog("请先选择一个用户!", Title.Warning);
                return;
            }
            App.MessageBox.ShowDialog("是否确认删除该用户?", new Action(DelUserAction), Title.Information);
         
        }

           void dclient_DeleteUserCompleted(object sender, DeleteUserCompletedEventArgs e)
        {
       
            string msg = string.Empty;
            try
            {
                if (e.Result==("true"))
                {
                    msg = "删除用户成功!";
                }
                else
                {
                    msg = "删除用户失败:" + e.Result;

                }
            }
            catch (Exception ex)
            {
                msg = "删除用户异常：" + ex.Message;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(msg);
            }
            
        }

           private void IDCBox_Click(object sender, RoutedEventArgs e)
           {
               StaffIDTB.IsReadOnly = !IDCBox.IsChecked.Value;
               StaffNameTB.IsReadOnly = !IDCBox.IsChecked.Value;
               if (IDCBox.IsChecked.Value)
               {
                   ChannelCBox.IsChecked = false;

                   ChannelIDTB.IsReadOnly = true;
                   ChannelNameTB.IsReadOnly = true;
               }
               
           }

           private void ChannelCBox_Click(object sender, RoutedEventArgs e)
           {
               ChannelIDTB.IsReadOnly = !ChannelCBox.IsChecked.Value;
               ChannelNameTB.IsReadOnly = !ChannelCBox.IsChecked.Value;
               if (ChannelCBox.IsChecked.Value)
               {
                   IDCBox.IsChecked = false;

                   StaffIDTB.IsReadOnly = true;
                   StaffNameTB.IsReadOnly = true;
               }
           }

           private void UpdateUserBtn_Click(object sender, RoutedEventArgs e)
           {
               if(string.IsNullOrEmpty(this.StaffIDTB.Text))
               {
                   return;
               }

               if (string.IsNullOrEmpty(this.StaffNameTB.Text)
               || string.IsNullOrEmpty(this.ChannelIDTB.Text)
               || string.IsNullOrEmpty(this.PasswordTB.Password)
               || this.LevelCBox.SelectedIndex < 0)
               {
                   App.MessageBox.ShowDialog("请完整填写所有信息!", Title.Warning);
                   return;
               }

                 Regex email = new Regex(DataHelper.EmailRegexString);
            if (!email.IsMatch(EmailTB.Text))
            {
                App.MessageBox.ShowDialog("请正确填写邮箱地址", Title.Warning);
                return;
            }

               try
               {
                  UserService.UpdateUserAsync(new UserInfor
                         {
                             User_ID = this.StaffIDTB.Text,
                             UserName = this.StaffNameTB.Text,
                             Channel_ID = this.ChannelIDTB.Text,
                             Password = this.PasswordTB.Password,
                             AdminLevel = this.LevelCBox.SelectedIndex,
                             Tel = TelTB.Text,
                             Email= EmailTB.Text,
                             IsDel = (LevelCBox.SelectedIndex == 0 ? '0' : '1'),
                             UpdateID=App.CurrentUser.UserID,
                             UpdateTime=DateTime.Now
                         });
                   this.Cursor = Cursors.Wait;
               }
               catch 
               {
                   App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
               }
           }

           private void ResultGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
               if (this.ResultGrid.SelectedItem != null)
               {
                   VW_UserWithChannel user = this.ResultGrid.SelectedItem as VW_UserWithChannel;
                   this.StaffIDTB.Text = user.UserID;
                   this.StaffNameTB.Text = user.UserName;
                   this.ChannelIDTB.Text = user.ChannelID;
                   this.ChannelNameTB.Text = user.ChannelName;
                   this.PasswordTB.Password = user.Password;
                   this.LevelCBox.SelectedIndex = user.IsDel=='0' ? 0:1;
                   this.TelTB.Text = string.IsNullOrEmpty(user.Tel) ? string.Empty : user.Tel;
                   this.EmailTB.Text = string.IsNullOrEmpty(user.Email) ? string.Empty : user.Email;
                   this.IsReadOnly = false;
                   this.StaffIDTB.IsReadOnly = true;
                   this.ChannelNameTB.IsReadOnly = true;
                   this.PasswordTB.IsEnabled = false;

                   AuthPage.Tag = user.UserID;
                   SelectedUserTB.Text = string.Format("[{0}]{1}", user.UserID, user.UserName);

               }
           }
           void AuthsGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
           }

           private void AuthCmBtn_Click(object sender, RoutedEventArgs e)
           {
               if (AuthsGrid.ItemsSource == null)
               {
                   App.MessageBox.ShowDialog("没有需要提交的数据");
                   return;
               }
               List<UserAuthEntity> uaeList = AuthsGrid.ItemsSource as List<UserAuthEntity>;
               List<int> authList = new List<int>();
               bool isAllDelete = false;
               foreach (UserAuthEntity u in uaeList)
               {
                   if (u.IsChecked)
                   {
                       authList.Add(u.Auth_ID);
                   }
                   else if(!string.IsNullOrEmpty(u.User_ID))
                   {
                       isAllDelete =  true;
                   }
               }
               if (authList.Count == 0 && !isAllDelete)
               {
                   App.MessageBox.ShowDialog("没有需要提交的数据");
                   return;
               }
               try
               {
                  UserService.UpdateUserAuthAsync(App.CurrentUser.UserID,
                              AuthPage.Tag.ToString(), authList);
                   AuthCmBtn.IsEnabled = false;
                   RefreshCmBtn.IsEnabled = false;
                   authLoading.Show();
               }
               catch 
               {
                   App.MessageBox.ShowDialog("连接服务器失败");
                   return;
               }

           }

           private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
               TabControl tab = sender as TabControl;
               if (tab.SelectedItem != null)
               {
                   if ((tab.SelectedItem as TabItem) == AuthPage)
                   {
                       RefreshCmBtn_Click(null, null);
                   }
               }
           }

           private void RefreshCmBtn_Click(object sender, RoutedEventArgs e)
           {
               if (this.AuthPage.Tag != null)
               {
                   try
                   {
                      UserService.GetUserAuthAsync(AuthPage.Tag.ToString());
                       RefreshCmBtn.IsEnabled = false;
                       authLoading.Show();
                   }
                   catch
                   {
                       App.MessageBox.ShowDialog("连接服务器失败");
                      
                   }
               }
           }



           void UserClient_UpdateUserAuthCompleted(object sender, UpdateUserAuthCompletedEventArgs e)
           {
               try
               {
                   if (e.Result)
                   {
                       App.MessageBox.ShowDialog("操作成功");
                   }
                   else
                   {
                       App.MessageBox.ShowDialog("操作失败");
                   }
               }
               catch
               {

                   App.MessageBox.ShowDialog("操作失败");
               }
               finally
               {
                   AuthCmBtn.IsEnabled = true;
                   RefreshCmBtn.IsEnabled = true;
                   authLoading.Stop();
               }
           }

           void UserClient_GetUserAuthCompleted(object sender, GetUserAuthCompletedEventArgs e)
           {
               try
               {
                   if (e.Result == null)
                   {
                       App.MessageBox.ShowDialog("查询失败，请稍后再试");
                   }
                   else
                   {

                       AuthsGrid.ItemsSource = e.Result;
                       

                   }
               }
               catch (Exception ex)
               {

                   App.MessageBox.ShowDialog("查询失败，" + ex.Message);
               }
               finally
               {
                   RefreshCmBtn.IsEnabled = true;

                   this.authLoading.Stop();
               }
           }

           private void ClearBtn_Click(object sender, RoutedEventArgs e)
           {
               Clear();
           }


           #region 渠道管理
           private void ChGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
               if (ChGrid.SelectedItem != null)
               {
                   VW_ChannelWithDistrict ch = ChGrid.SelectedItem as VW_ChannelWithDistrict;
                   ChannelIDTB2.Text = ch.Id;

                   ChannelNameTB2.Text = ch.ChannelName;
                   AreaCBox.SelectedItem =string.Format("[{0}]{1}",ch.CountyCode,ch.CountyName);

                   DisSelectedItem = string.Format("[{0}]{1}", ch.District_ID, ch.District_Name);


                   SetCHPageReadOnly(true);
               }
           }
           string DisSelectedItem = string.Empty;
           private void QueryBtn2_Click(object sender, RoutedEventArgs e)
           {
               if (string.IsNullOrEmpty(ChannelIDTB2.Text)
                   && string.IsNullOrEmpty(ChannelNameTB2.Text))
               {
                   App.MessageBox.ShowDialog("渠道编号和渠道名称至少填写一个");
                   return;
               }
               try
               {
                   UserService.GetChannelAsync(ChannelIDTB2.Text, ChannelNameTB2.Text);

                   QueryBtn2.IsEnabled = false;
                   NewBtn2.IsEnabled = false;
                   UpdateBtn2.IsEnabled = false;
                   CmtBtn2.IsEnabled = false;
                   ClearBtn2.IsEnabled = false;
                   chLoading.Show();
               }
               catch 
               {

                   App.MessageBox.ShowDialog("连接服务器失败");
               }

           }

           void UserService_GetChannelCompleted(object sender, GetChannelCompletedEventArgs e)
           {
               try
               {
                   if (e.Result == null)
                   {
                       ChGrid.ItemsSource = null;
                       App.MessageBox.ShowDialog("查询渠道失败,后台数据异常");
                   }
                   else if (e.Result.Count == 0)
                   {
                       ChGrid.ItemsSource = null;
                       App.MessageBox.ShowDialog("没有查询到数据");
                   }
                   else
                   {
                       ChGrid.ItemsSource = e.Result;
                   }
               }
               catch
               {
                   App.MessageBox.ShowDialog("查询渠道失败,请稍后再试");
               }
               finally
               {
                   QueryBtn2.IsEnabled = false;
                   NewBtn2.IsEnabled = true;
                   UpdateBtn2.IsEnabled = true;
                   CmtBtn2.IsEnabled = false;
                   ClearBtn2.IsEnabled = true;
                   chLoading.Stop();
               }
           }

           private void NewBtn2_Click(object sender, RoutedEventArgs e)
           {
               ClearBtn2_Click(null, null);
               QueryBtn2.IsEnabled = false;
               NewBtn2.IsEnabled = false;
               UpdateBtn2.IsEnabled = false;
               CmtBtn2.IsEnabled = true;
               ClearBtn2.IsEnabled = true;
           }

           private void UpdateBtn2_Click(object sender, RoutedEventArgs e)
           {
               SetCHPageReadOnly(false);

               QueryBtn2.IsEnabled = false;
               NewBtn2.IsEnabled = false;
               UpdateBtn2.IsEnabled = false;
               CmtBtn2.IsEnabled = true;
               ClearBtn2.IsEnabled = true;
           }

           private void CmtBtn2_Click(object sender, RoutedEventArgs e)
           {
               if (string.IsNullOrEmpty(ChannelIDTB2.Text)
                   || string.IsNullOrEmpty(ChannelNameTB2.Text)
                   || AreaCBox.SelectedItem == null
                   || DisCBox.SelectedItem == null)
               {
                   App.MessageBox.ShowDialog("请完善各项信息");
                   return;
               }
               if (!ChannelRegex.IsMatch(ChannelIDTB2.Text))
               {
                   App.MessageBox.ShowDialog("渠道编号非法");
                   return;
               }
               try
               {
                   UserService.UpdateChannelAsync(ChannelIDTB2.Text, ChannelNameTB2.Text,
                              App.GetID(AreaCBox.SelectedItem.ToString()).ToString(),
                        App.GetID(DisCBox.SelectedItem.ToString()).ToString(), App.CurrentUser.UserID);
                   QueryBtn2.IsEnabled = false;
                   NewBtn2.IsEnabled = false;
                   UpdateBtn2.IsEnabled = false;
                   CmtBtn2.IsEnabled = false;
                   ClearBtn2.IsEnabled = false;
                   chLoading.Show();
               }
               catch
               {

                   App.MessageBox.ShowDialog("连接服务器失败");
               }
           }

           void UserService_UpdateChannelCompleted(object sender, UpdateChannelCompletedEventArgs e)
           {
              try
               {
                   if (e.Result==-1)
                   {
                       App.MessageBox.ShowDialog("查询渠道失败,后台数据异常");
                   }                 
                   else
                   {
                       
                       App.MessageBox.ShowDialog("操作成功");
                   }
               }
               catch
               {
                   App.MessageBox.ShowDialog("查询渠道失败,请稍后再试");
               }
               finally
               {
                   QueryBtn2.IsEnabled = false;
                   NewBtn2.IsEnabled = true;
                   UpdateBtn2.IsEnabled = true;
                   CmtBtn2.IsEnabled = false;
                   ClearBtn2.IsEnabled = true;
                   SetCHPageReadOnly(e.Result == 0);
                   chLoading.Stop();
               }
           

           }

           void UserService_GetDistrictCompleted(object sender, GetDistrictCompletedEventArgs e)
           {
               try
               {
                   if (e.Result == null)
                   {

                       App.MessageBox.ShowDialog("获取片区失败，后台服务异常");
                   }
                   else
                   {
                       DisCBox.Items.Clear();
                       foreach (string s in e.Result)
                       {
                           DisCBox.Items.Add(s);
                       }
                       if (!string.IsNullOrEmpty(DisSelectedItem))
                       {
                           DisCBox.SelectedItem = DisSelectedItem;
                       }
                   }
               }
               catch
               {

                   App.MessageBox.ShowDialog("获取片区失败，请稍后再试");
               }
           }

           void UserService_GetAreaCompleted(object sender, GetAreaCompletedEventArgs e)
           {
               try
               {
                   if (e.Result == null)
                   {
                       App.MessageBox.ShowDialog("获取县区失败，后台服务异常");
                   }
                   else
                   {
                       if (AreaCBox.Items.Count > 0)
                       {
                           AreaCBox.Items.Clear();
                       }
                       foreach (string s in e.Result)
                       {
                           AreaCBox.Items.Add(s);
                       }
                   }
               }
               catch 
               {

                   App.MessageBox.ShowDialog("获取县区失败，请稍后再试");
               }
           }

           private void AreaCBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
           {
               if (AreaCBox.SelectedItem != null)
               {
                   try
                   {
                       UserService.GetDistrictAsync(App.GetID(AreaCBox.SelectedItem.ToString()).ToString(), Guid.NewGuid());
                   }
                   catch 
                   {
                       App.MessageBox.ShowDialog("连接服务器失败");
                   }
               }

           }

           private void ClearBtn2_Click(object sender, RoutedEventArgs e)
           {
               ChannelIDTB2.Text = string.Empty;
              
               ChannelNameTB2.Text = string.Empty;
               AreaCBox.SelectedIndex = -1;

               DisCBox.SelectedIndex = -1;
               DisSelectedItem = string.Empty;

               QueryBtn2.IsEnabled = true;
               NewBtn2.IsEnabled = true;
               UpdateBtn2.IsEnabled = false;
               CmtBtn2.IsEnabled = false;
               ClearBtn2.IsEnabled = true;

               ChGrid.ItemsSource = null;

               SetCHPageReadOnly(false);
           }

           void SetCHPageReadOnly(bool isReadOnly)
           {
               ChannelIDTB2.IsReadOnly = isReadOnly;
               ChannelNameTB2.IsReadOnly = isReadOnly;
               AreaCBox.IsEnabled = !isReadOnly;
               DisCBox.IsEnabled = !isReadOnly;
           }
         
        #endregion

           

           

    }
}
